package com.utf999.qiangmanger.listener;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.utf999.qiangmanger.exception.BizException;
import com.utf999.qiangmanger.filter.SQLFileFilter;
import com.utf999.qiangmanger.utils.SQLUtils;


/**
 * 为WEB工程提供HQL文件初始化的监听类。
 * @author wenjie
 */
public class SQLFileListener implements ServletContextListener {
	
	/**
	 * log日志打印
	 */
	private static Log LogSQLFile = LogFactory.getLog(SQLFileListener.class);
	
	public void contextInitialized(ServletContextEvent contextEvent) {
		String sqlFile = contextEvent.getServletContext().getInitParameter("sqlFile");
		//如果没有sqlFile信息，则默认为/WEB-INF/classes/sqlfile/*.sql.xml
		if(StringUtils.isEmpty(sqlFile)) {
			sqlFile = "/WEB-INF/classes/sqlfile/*.sql.xml";
		} 
		
		List<File> files = new ArrayList<File>();
		String[] sqlFiles = sqlFile.split(",");
		String parentPath = contextEvent.getServletContext().getRealPath("/");
		for (String chileUrl : sqlFiles) {
			chileUrl = chileUrl.trim();
			int lastIndex = chileUrl.lastIndexOf("/");
			String path = chileUrl.substring(0, lastIndex);
			String pattern = chileUrl.substring(lastIndex + 1);
			
			File[] filesArray = getFileList(parentPath, path, pattern);
			if(filesArray != null) {
				List<File> fileList = Arrays.asList(filesArray);
				files.addAll(fileList);
			}
		}
		if(!files.isEmpty()) {
			SQLUtils sqlUtils = SQLUtils.createSQLUtils();
			try {
				//开始进行sql、hql文件的解析
				sqlUtils.setSqlFiles(files);
			} catch (BizException e) {
				SQLFileListener.LogSQLFile.error(e.getMessage(), e);
			}
		}
	}

	public void contextDestroyed(ServletContextEvent contextEvent) {
		
	}
	
	private File[] getFileList(String parentFile, String chileFile, String pattern) {
		return getFileList(new File(parentFile), chileFile, pattern);
	}
	
	private File[] getFileList(File parentFile, String chileFile, String pattern) {
		File file = new File(parentFile, chileFile);
		return file.listFiles(new SQLFileFilter(pattern));
	}
}
